
var cloudwalkobj; //document.createElement("object");
var width=640;	//640  400  320
var height=480;	//宽高比为4：3
var n_ok = 0;
var n_fail = 0;
var g_iCamera = 0; //要打开的摄像头索引。-- jinfude add。2018-08-14
var rotatemode = 0;	//0正常、1顺时针90度、2逆时针90度。3-已经工作在镜子模式的摄像头
var g_width = 0;
var g_height = 0;
//var m_bSpcialOption = false; //是否出现过张嘴或眨眼

var CW_nLiveNum = 1;		//活体检测次数**
var CW_nLiveLevel = 1;		//活体难度**
var CW_nfaceValue = 0.84;    //人脸阈值**
var qualityThreshold = 0.75;   //质量阈值**
var serverIp = "10.11.51.214:7010";  //服务器地址**

var n_LiveTime = 0;
var n_LiveOptionNum = 6; //常量：可检测的动作个数有 6 个。
var g_optarr = [0,0,0,0,0,0]; //标记每个动作是否已经使用过1张嘴2抬头3低头4右转头5左转头6眨眼
var strLicense = "";
var g_bNeedHack = false; //是否需要后端防 HACK
var m3url = "";

// var cameraId;
// var cameraName;


function showDownloadNotice(){
	//alert("人脸识别控件未安装");
	$("#downloadNotice").removeClass("hide");
	$("#downloadNotice").addClass("show");
	$("#rside").addClass("hide");
}

function showNewVersionNotice(){
	$("#newVersionNotice").removeClass("hide");
	$("#newVersionNotice").addClass("show");
	$("#rside").addClass("hide");
}
// 刷新页面
function refreshPage(){
	window.location.href="livedetect.html";   //刷新页面
}
//页面加载后调用
function onPageLoad()
{
	var nodeA = document.getElementById("cloudwalkwebobj");
	var bSuccess = createPlugin(nodeA);
	
	hideocx(); //隐藏 ocx
	if(bSuccess) {
		var cbCameras = document.getElementById("cbCameras");
		var strJson = cloudwalkobj.cwQueryCamera();
		var jsonObj = $.parseJSON(strJson);

		if (jsonObj && jsonObj.list.length > 0) {
			g_iCamera = jsonObj.list[0].DeviceId;
		} else {
			// var result = confirm("未安装人脸检测插件,是否要安装？");
			//if(result) {
			//	downOcx();
			//}
			alert("未安装摄像头");
			return;
		}

		// for(i = 0; i < jsonObj.count; i++)
		// {
		// 	var item = document.createElement('option');
		// item.text = "[" + i + "] " + jsonObj.list[i].DeviceName;
		// item.value = jsonObj.list[i].DeviceId;
		// //注：IE7 不支持 add() 的第二个参数。
		// cbCameras.add(item);
		// }

		// 设置hack检测服务器IP，在代码里面固定，不读取ocx配置，避免需要在客户端设置IP相关信息
		// var ip = "192.168.1.11";
		// serverIp = ip;
		var jsInfo = new Object();
		jsInfo.ip = serverIp;
		jsInfo.hackServerIp = serverIp;
		cloudwalkobj.cwSetConfig(JSON.stringify(jsInfo));

		var config = cloudwalkobj.cwGetConfig();
		// console.log(config);
		PraseConfig(config);

		livedetectfunction();
	}
}

//targetE: 是 DOM 中的一个节点。
function createPlugin(targetE) 
{
	//因为点击按钮时，IE 8 会重复调用到这个函数。2018-08-17
	var bIsNull = false;
	if(cloudwalkobj === undefined)
		bIsNull = true;
	
	if(!bIsNull)
	{
		return;
	}
	
	var bDet = BrowserDetect.browser;
	if("Explorer" == bDet)
	{
		//IE: use OCX;
		cloudwalkobj = document.createElement("object");
		cloudwalkobj.id = "IE_CloudWalkSDKPlugin";
		cloudwalkobj.classid = "CLSID:B1597418-A51E-4140-8698-EE865439755C";
	}
	else
	{
		cloudwalkobj = document.createElement("embed");	
		cloudwalkobj.id = "FF_CloudWalkSDKPlugin";
		cloudwalkobj.type = "application/x-cloudface-sdk3.0";
	}
	if(rotatemode == 0 || rotatemode == 3)
	{
		cloudwalkobj.width = width;
		cloudwalkobj.height = height + 130;
	}
	else
	{
		cloudwalkobj.width = height;
		cloudwalkobj.height = width + 130;
	}
	targetE.appendChild(cloudwalkobj);
	if(!cloudwalkobj.valid) 
	{
		// alert("内存不足！请点击右上角<关于云从>，并稍等片刻。");
                        var result = confirm("未安装人脸检测插件,是否要安装？");
                        if(result) {
                                downOcx();
                        }

		return false;
	}
	// var config = cloudwalkobj.cwGetConfig();
	// PraseConfig(config);
	return true;
}

//开始活体检测
function startRandomLiveDetect() 
{
	// var chkNeedHack = document.getElementById("chkNeedHack");
	g_bNeedHack = true; // chkNeedHack.checked;
	showocx();
	// var cbCameras = document.getElementById("cbCameras");
	// 	// g_iCamera = eval(cbCameras.value);
	
	
	var nRet = cloudwalkobj.cwStartCamera(g_iCamera, rotatemode);
	if(nRet != 0)
	{
		var msg;
		switch(nRet)
		{
			case CW_ERR_CameraNotOpen:
				msg = "摄像头未打开！";
				break;
			case CW_ERR_CameraOpenError:
				msg = "摄像头打开失败！";
				break;
			case CW_ERR_CameraOpenAdy:
				msg = "摄像头已经打开！";
				break;
			default:
				msg = "摄像头打开失败 ！错误码："+ nRet;
				break;
		}
		alert(msg);
		window.location.href="livedetect.html"; 
		return;
	}
	cloudwalkobj.cwSaveBestFacePic(1);
	if(g_bNeedHack && CW_nLiveNum <= 1){
		// console.log("jinru");
		cloudwalkobj.cwNeedHack(1);
	}
		
	var opt = getRandomIndexPOC();
	// console.log(opt);
	
	cloudwalkobj.cwStartLiveDetect(opt);
}

function testPost() {
	window.parent.postMessage(JSON.stringify({
		"workerId": '123456',
		"workerName": '',
		"workerDepartment": "",
		"workerTitle": ""
	}),"*");
}

function closeLiveCheck() {
	// alert("关闭人脸");
        window.parent.postMessage(JSON.stringify({
                "workerId": '',
                "workerName": '',
                "workerDepartment": "",
                "workerTitle": ""
        }),"*");
}

function downOcx() {
	window.open("http://10.11.51.214:8000/ocx/liveocx.rar");
}

function liveDetectEvent(jsonStr) 
{
	var jsonobject = $.parseJSON(jsonStr);
	// toErrorPage(jsonobject.Result);
	// alert(jsonStr);
	// console.log(jsonStr);
	if(jsonobject.Result == 0)
	{
		if(n_LiveTime >= CW_nLiveNum)
		{
			// console.log(jsonobject);
			var ImaData = cloudwalkobj.cwGetBestFace();
			var ImageData = $.parseJSON(ImaData);						
			
			cloudwalkobj.cwStopCamera();
			cloudwalkobj.cwStoptLiveDetect();
			cloudwalkobj.cwDestory();
			// 人脸比对
			$.ajax({
				//请求方式
				type : "POST",
				//请求的媒体类型
				contentType: "application/json;charset=UTF-8",
				url : "/face/recog/group/identify/ext1",
				data : JSON.stringify({
					"groupId": "GP0004",
					"img": ImageData.data
				}),
				//请求成功
				success : function(res) {
					if (res.result === 0) { //上传成功

						var besefaceImg = document.getElementById("showmanobj");
						var scoreNo = res.faces[0].score;  //取到对比相似度
						var getFaceId = res.faces[0].faceId;  //取到照片id
						besefaceImg.src = "data:image/jpeg;base64," + ImageData.data;
						hideocx();

						var file = [];
						if (scoreNo > CW_nfaceValue) {
							document.getElementById("score").innerHTML = "人脸相似度：" + " " + scoreNo;
							document.getElementById("info").innerHTML = "验证通过";
							document.getElementById("info").style.color = "green";
							file['mp3'] = '../music/success.mp3';

							audioplayer('audioplane', file, false);

							$.ajax({
								//请求方式
								type : "POST",
								//请求的媒体类型
								contentType: "application/json;charset=UTF-8",
								url : "/face/clustering/face/query",
								data : JSON.stringify({
									"type": "queryByFaceId",
									"groupId": "GP0004",
									"faceId": getFaceId
								}),
								//请求成功
								success : function(res) {
									if (res.result === 0) {
										// console.log(res);
										var getName = res.rows[0].tag;
										// alert(getName);
										// var allName = getName.split('_');
										// var userName = allName[0];
										// var workNo = allName[1];
										// console.log(userName);
										// console.log(workNo);
										var workNo = getName.substring(0, 6);
										var userName = getName.substring(6);

										var confirmResult=confirm("工号：" + workNo + ",确定要提交吗？");
										if (confirmResult) {
											// alert("postMessage");
											window.parent.postMessage(JSON.stringify({
												"workerId": workNo,
												"workerName": userName,
												"workerDepartment": "",
												"workerTitle": ""
											}),"*");
										}
									} else {
										alert(res.info);
										refreshPage();
									}
								},
								error : function(e){
									alert(e.responseText);
									refreshPage();
								}
							});
						} else {
							document.getElementById("score").innerHTML = "人脸相似度：" + " " + scoreNo;
							document.getElementById("info").innerHTML = "验证失败";
							document.getElementById("info").style.color = "#CE4242";

							setTimeout(function () {
								refreshPage();
							},1500);
						}
					} else {
						alert(res.info);
						refreshPage();
					}
				},
				//请求失败，包含具体的错误信息
				error : function(e){
					alert(e.responseText);
					refreshPage();
				}
			});
			// toSuccessPage();
		}
		else
		{
			if(g_bNeedHack && (n_LiveTime == (CW_nLiveNum - 1)))
				cloudwalkobj.cwNeedHack(1);
			var opt = getRandomIndexPOC();
			cloudwalkobj.cwStartLiveDetect(opt); 
		}
	}
	else
	{
		//注意，cwStoptLiveDetect 接口名称里面多写了一个 t -- comment by jinfude
		cloudwalkobj.cwStopCamera();
		cloudwalkobj.cwStoptLiveDetect();
		cloudwalkobj.cwDestory();
		// toErrorPage(jsonobject.Result);
		// var file = [];
		// file['mp3'] = '../music/failed.mp3';
		// audioplayer('audioplane', file, false);

		setTimeout(function () {
			refreshPage();
		},500);
	}
}

function toErrorPage(rt){
	switch(rt)
	{
		case CW_NoFace:
			//未检测到人脸
			window.location.href="failure1.html"; 
			break;
		case CW_LostFace:
			//人脸丢失
			window.location.href="failure2.html"; 
			break;
		case CW_ShakeFace:
			//人脸晃动
			window.location.href="failure2.html"; 
			break;
		case CW_DetectLieveTimeOut:
			//检测超时
			window.location.href="failure3.html"; 
			break;
		default:
			window.location.href="failure2.html"; 
			break;
	}
}

function toSuccessPage() {
	window.location.href="success.html"; 
}

function livedetectfunction()
{
	$("#showmanobj").css('display','none'); 
	$("#jianceobj").css('display','none');
	
	var el = document.getElementById("cloudwalkwebobj");
	createPlugin(el);
	
	registerCallBack(cloudwalkobj, "cwLivesInfoCallBack", liveDetectEvent);

	var nret = cloudwalkobj.cwInit(strLicense);
	if(nret != 0)
	{
		var msg = "初始化SDK失败错误码：" + nret;
		alert(msg);
		return;
	}
	
	cloudwalkobj.cwSetLiveDetectLevel(CW_nLiveLevel);
	InitArry();
	startRandomLiveDetect();
}
		
function getRandomIndex()
{
	//动作个数为 0，则只需要做一个准备阶段即可；
		if(CW_nLiveNum == 0)
		{
			n_LiveTime = n_LiveTime + 1;
			return 0;
		}
	 //产生下一个动作
	  var nrandom = Math.random() * n_LiveOptionNum;
	  var id = Math.floor(nrandom);
	  var buse = g_optarr[id];
	  
	  while(buse == 1)
	  {  
			id = (id + 1) % n_LiveOptionNum;
			buse = g_optarr[id];
	  }
	  
	  n_LiveTime = n_LiveTime + 1;
	  g_optarr[id] = 1;
	  
	  if(n_LiveTime >= CW_nLiveNum)
	  {
		  InitArry();
	  }
	  	  
	  return (id + 1);
}

var arr = new Array();

function getRandomIndexPOC()
{
	//动作个数为 0，则只需要做一个准备阶段即可；
	
	
	var opt = -1;
	
	if(CW_nLiveNum == 0)
	{
		opt = 1;
		n_LiveTime = n_LiveTime + 1;
		return 0;
	}
	else if(CW_nLiveNum == 1)
	{
		var arr1 = [1,6];   //此处如果需要左转头右转头在数组添加4，5
		opt = getRandomNumInArray(arr1);
	}
	else if(CW_nLiveNum == 2 && n_LiveTime == 0)
	{
		// var arr1 = [6,1];//此处如果需要左转头右转头把数组内改为4，5
		// var arr2 = [1, 6];
		
		// var opt1 = getRandomNumInArray(arr1);
		// var opt2 = getRandomNumInArray(arr2);
		// arr[0] = opt1;
		// arr[1] = opt2;

		arr = [1,6];
		opt = getRandomNumInArray(arr);
		
		var index = 0;
		for(; index < CW_nLiveNum - n_LiveTime; index++) {
			if(arr[index] == opt)
			{
				arr.splice(index, 1);
			}
		}
	}
	else if(CW_nLiveNum == 3 && n_LiveTime == 0)
	{
		var arr1 = [];//此处如果需要左转头右转头把数组内改为4，5
		var arr2 = [1, 6];
		
		var arr3 = new Array();
		var opt1 = getRandomNumInArray(arr1);
		var opt2 = getRandomNumInArray(arr2);
		arr[0] = opt1;
		arr[1] = opt2;
		
		if(opt1 == arr1[0])
		{
			arr3[0] = arr1[1];
		}
		else{
			arr3[0] = arr1[0];
		}
		
		if(opt2 == arr2[0])
		{
			arr3[1] = arr2[1];
		}
		else{
			arr3[1] = arr2[0];
		}
		
		var opt3 = getRandomNumInArray(arr3);
		arr[2] = opt3;
		
		opt = getRandomNumInArray(arr);
		// console.log(opt);
		var index = 0;
		for(; index < CW_nLiveNum - n_LiveTime; index++) {
			if(arr[index] == opt)
			{
				arr.splice(index, 1);
				// console.log(arr);
			}
		}
		
	}
	else if(CW_nLiveNum == 4 && n_LiveTime == 0)
	{
		arr[0] = 1;
		arr[1] = 6;//此处如果需要左转头数组内改为4
		// arr[2] = 5;
		// arr[3] = 6;
		opt = getRandomNumInArray(arr);
		var index = 0;
		for(; index < CW_nLiveNum - n_LiveTime; index++) {
			if(arr[index] == opt)
			{
				arr.splice(index, 1);
			}
		}
	}
	else
	{
		opt = getRandomNumInArray(arr);		
		
		var index = 0;
		for(; index < CW_nLiveNum - n_LiveTime; index++) {
			if(arr[index] == opt)
			{
				arr.splice(index, 1);
			}
		}
		
	}
		
	//产生下一个动作POC
	/*var opt = -1;
	if(CW_nLiveNum == 1)
	{
		//var myarray = [1,6];
		var myarray = [1, 4, 5, 6]; //张嘴眨眼取一个
		opt = getRandomNumInArray(myarray);
	}
	else if(CW_nLiveNum == 2)
	{
		if(g_optarr[0] == 1)
		{
			opt = 6;
		}
		else if(g_optarr[5] == 1)
		{
			opt = 1;
		}
		else
		{
			//var myarray = [1,6];
			var myarray = [1, 4, 5, 6];
			opt = getRandomNumInArray(myarray);
		}	
	}
	else
	{
		if(g_optarr[0] != 1 && g_optarr[5] != 1 && (CW_nLiveNum - n_LiveTime) == 2)
		{
			//var myarray = [1,6];
			var myarray = [1, 4, 5, 6];
			opt = getRandomNumInArray(myarray);
		}
		else if((CW_nLiveNum - n_LiveTime) == 1 && (g_optarr[0] == 0 || g_optarr[5] == 0))
		{
			if(g_optarr[0] == 0)
			{
				opt = 1;
			}
			else if(g_optarr[5] == 0)
			{
				opt = 6;
			}
		}
		else
		{
			var myarray = new Array();
			for(var i = 0; i < n_LiveOptionNum; i++)
			{
				if(g_optarr[i] == 0)
				{
					myarray.push(i+1);
				}
			}
			opt = getRandomNumInArray(myarray);
		}
	}
	
	if(opt >= 1)
	{
		var index = opt - 1;
		g_optarr[index] = 1;
	}*/
	
	
	n_LiveTime = n_LiveTime + 1;
	return opt;
}

function getRandomNumInArray(arr)
{
	var nLength = arr.length;
	var nrandom = Math.random()*nLength;
	nrandom = Math.floor(nrandom);
	var opt = arr[nrandom];
	return opt;
}

//函数名称把 Parse 拼错了。将就一下吧。哎。。
function PraseConfig(strJson)
{
	var jsonObj = $.parseJSON(strJson);
	if(jsonObj != "null")
	{
	 	//  CW_nLiveNum = parseInt(jsonObj["LiveDetectTimes"]);
		//  CW_nLiveLevel = parseInt(jsonObj["LiveDetectLevel"]);
		 strLicense = jsonObj["License"];

		//  serverIp = jsonObj["ip"];
		//  CW_nfaceValue = jsonObj["faceValue"];

		// var last=JSON.stringify(jsInfo);
		// var nRet = cloudwalkobj.cwSetConfig(last);
	}
}

function InitArry()
{
	for(var i = 0; i < n_LiveOptionNum; i++)
	{ 
		// g_optarr[i] = 0;  此处初始化添加if条件
		if (i == 0 || i == 5) {
			g_optarr[i] = 0;
		}
		
	}
	//poc 开启
	//g_optarr[2] = 1; //点头去掉
}

function showocx()
{
	$("#showmanobj").css('display','none'); 
	$("#jianceobj").css('display','none');
	
	//$("#cloudwalkwebobj").css('display','block');
	var node1 = document.getElementById("cloudwalkwebobj");
	node1.style.display = "block";
	node1.style.visibility = "visible";
	node1.style.width = cloudwalkobj.width;
	node1.style.height = cloudwalkobj.height;
}

function hideocx()
{
	$("#showmanobj").css('display','block'); 
	$("#jianceobj").css('display','block');
	
	//$("#cloudwalkwebobj").css('display','block');
	var node1 = document.getElementById("cloudwalkwebobj");
	node1.style.display = "block";
	node1.style.visibility = "hidden";
	node1.style.width = 1;
	node1.style.height = 1;
}

